package com.sskj.base.view;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ViewFlipper;

import com.sskj.base.utils.ClickUtil;

import java.util.List;

public class NoticeView extends ViewFlipper {
    private OnItemClickListener listener;
    private Adapter adapter;
    private int flipInterval = 2000;

    public NoticeView(Context context) {
        super(context);
        init();
    }

    public NoticeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void init() {
        setFlipInterval(flipInterval);
    }

    private void setData() {
        if (adapter == null) {
            return;
        }
        for (int i = 0; i < adapter.getCount(); i++) {
            int position = i;
            View view = LayoutInflater.from(getContext()).inflate(adapter.layoutId, null);
            view = adapter.bindView(view, adapter.getItem(position));
            ClickUtil.click(view, view1 -> {
                if (listener != null) {
                    listener.onClick(position);
                }
            });
            addView(view);
        }
        startFlipping();
    }

    public void setAdapter(Adapter adapter) {
        this.adapter = adapter;
        setData();
    }


    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        void onClick(int position);
    }

    public abstract static class Adapter<T> {

        List<T> data;
        int layoutId;

        public Adapter(@LayoutRes int layoutId, List<T> data) {
            this.data = data;
            this.layoutId = layoutId;
        }

        public T getItem(int position) {
            return data.get(position);
        }

        public int getCount() {
            return data.size();
        }

        public abstract View bindView(View view, T item);

    }

}
